package cn.zs.supply.common.core.web.config;

import cn.zs.supply.common.constants.enums.PubErrCode;
import cn.zs.supply.common.core.domain.result.BaseResult;
import cn.zs.supply.common.core.domain.result.ResultBuilder;
import cn.zs.supply.common.core.exception.BusiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@Slf4j
public class BaseGlobalExceptionHandler {
    @ExceptionHandler(value = Throwable.class)
    public BaseResult defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        log.error("全局异常拦截器：", e);
        String contentType = req.getHeader("Content-Type");
        String accept = req.getHeader("accept");
        if ((contentType != null && contentType.toLowerCase().contains("application/json"))
                || (accept != null && accept.toLowerCase().contains("application/json"))) {
            if (e instanceof HttpMessageNotReadableException) {
                return ResultBuilder.genBaseResult(PubErrCode.PARAM_ERROR.getCode(), PubErrCode.PARAM_ERROR.getMsg() + ":" + e.toString());
            }
            if (e instanceof BusiException) {
                BusiException ex = (BusiException) e;
                return ResultBuilder.genBaseResult(ex.getCode(), ex.getMessage());
            } else {
                return ResultBuilder.genBaseResult(PubErrCode.COMMON_ERROR.getCode(), PubErrCode.COMMON_ERROR.getMsg() + ":" + e.toString());
            }
        }
        //TODO:modelandview
        if (e instanceof BusiException) {
            BusiException ex = (BusiException) e;
            return ResultBuilder.genBaseResult(ex.getCode(), ex.getMessage());
        }
        return ResultBuilder.genBaseResult(PubErrCode.COMMON_ERROR);
    }

}
